/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package kr.ac.kaist.pointdaproject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Demonstrates how to write an efficient list adapter. The adapter used in this example binds
 * to an ImageView and to a TextView for each row in the list.
 *
 * To work efficiently the adapter implemented here uses two techniques:
 * - It reuses the convertView passed to getView() to avoid inflating View when it is not necessary
 * - It uses the ViewHolder pattern to avoid calling findViewById() when it is not necessary
 *
 * The ViewHolder pattern consists in storing a data structure in the tag of the view returned by
 * getView(). This data structures contains references to the views we want to bind data to, thus
 * avoiding calls to findViewById() every time getView() is invoked.
 */
public class CardPredefinedListActivity extends ListActivity {

	private static final int USER_DIALOG = 1;
	
    private static class CardPredefinedListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private Resources mResources;

        public CardPredefinedListAdapter(Context context) {
        	mResources = context.getResources();
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return mResources.getStringArray(R.array.select_predefined_card_name).length;
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.predefined_list_item, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.name);
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);

                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            String textRes = mResources.getStringArray(R.array.select_predefined_card_name)[position];
            String iconRes = mResources.getStringArray(R.array.select_predefined_card_icon)[position];
            
            holder.text.setText(textRes);
            holder.icon.setImageResource(mResources.getIdentifier(iconRes, "drawable", "kr.ac.kaist.pointdaproject")); 
            
            return convertView;
        }

        static class ViewHolder {
            TextView text;
            ImageView icon;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.card_predefined);
		
        TextView mText = (TextView) findViewById(R.id.text);
        mText.setOnClickListener(new OnClickListener() {
            @SuppressWarnings("deprecation")
			public void onClick(View v) {
                showDialog(USER_DIALOG);
            }
        });
        //mText.setText("Enter your cards");
        
        // Use an existing ListAdapter that will map an array
        // of strings to TextViews
        setListAdapter(new CardPredefinedListAdapter(this));
        getListView().setOnItemClickListener(new OnItemClickListener() {  
			@Override 
			public void onItemClick(AdapterView<?> a, View v, int position, long id) {
				Resources res;
				
				res = CardPredefinedListActivity.this.getResources();
	            String textRes = res.getStringArray(R.array.select_predefined_card_name)[position];
	            String iconRes = res.getStringArray(R.array.select_predefined_card_icon)[position];

				Intent intent = new Intent();
				intent.putExtra("name", textRes);
				intent.putExtra("icon", iconRes);
				setResult(CardRegistration.REQUEST_PREDEFINED_CARD,intent);
				finish();
			}  
       });
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
    	if(id == USER_DIALOG){
    		createCardnameFromUser();
    	}
    	return null;
    }   
    
	private void createCardnameFromUser(){
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.alert_dialog_cardname_entry, null);
        new AlertDialog.Builder(this)
            /*
             * .setIconAttribute(android.R.attr.alertDialogIcon)
             * 
             */            
        	.setTitle(R.string.enter_card_name)
            .setView(textEntryView)
            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked OK so do some stuff */
                	EditText cardname = (EditText) textEntryView.findViewById(R.id.cardname_edit);
                	String name = cardname.getText().toString();
                	if(name.length() == 0) {
                		Toast.makeText(CardPredefinedListActivity.this, R.string.enter_card_name, Toast.LENGTH_SHORT).show();
                	} else {
        	            String icon = "card1";
        	            
        	            Intent intent = new Intent();
        				intent.putExtra("name", name);
        				intent.putExtra("icon", icon);
        				setResult(CardRegistration.REQUEST_PREDEFINED_CARD,intent);

        				CardPredefinedListActivity.this.finish();
                	}
                }
            })
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    /* User clicked cancel so do some stuff */
                }
            })
            .create()
            .show();
   }    
}

